#!/bin/bash
#
#Configure
#Please execute : sudo apt-get install lib32stdc++6 gcc-arm-linux-guneabihf 
#Please execute : sudo apt-get install build-essential device-tree-compiler
#Please execute : sudo apt-get install u-boot-tools

arch=arm
cross_compile=arm-linux-gnueabihf-
localversion="-cazure"
#Configure cross compiler
path="/home/chen/orangepi/gcc-linaro-arm-linux-gnueabihf-4.8/bin:"$PATH
export PATH=$path
#arm-linux-gnueabihf-gcc -v

ismenuconfig=yes #yes and no 
log_file="build.log"

#Compiling process
num=3
#show help
show_usage(){
	printf "Usage: \n ./build.sh [target board] \n --[zero|one|pc|pc_plus|plus2e|plus|2] \n\n"
	exit
}
#execute script and record log
run(){
	echo "" | tee -a $log_file
	echo $1 | tee -a $log_file
	$1 | tee -a $log_file
	echo "" | tee -a $log_file
}

echo "The Orangepi u-boot compiler script" | tee $log_file
date | tee -a $log_file

if [[ $1 == "clean" ]]; then
	run "make ARCH=$arch CROSS_COMPILE=$cross_compile clean"
	run "make ARCH=$arch CROSS_COMPILE=$cross_compile distclean"
	exit	
fi
if [[ $1 != "" ]]; then
	configfile="orangepi_$1_defconfig"
	if [[ -f .config ]]; then
		echo " .config file exist,ready to clean up"
		run "make ARCH=$arch CROSS_COMPILE=$cross_compile clean"
	fi
	#make xx_defconfig
	run "make ARCH=$arch CROSS_COMPILE=$cross_compile LOCALVERSION=$localversion $configfile"
	
	#make menuconfig
	if [[ $ismenuconfig == yes ]]; then 
		run "make ARCH=$arch CROSS_COMPILE=$cross_compile menuconfig" 
	fi
else
	show_usage
fi


run "make ARCH=$arch CROSS_COMPILE=$cross_compile LOCALVERSION=$localversion j=$num"

if [[ -f "u-boot-sunxi-with-spl.bin" ]]; then
	echo "Compile success"
	run "cp u-boot-sunxi-with-spl.bin orangepi_$1_u-boot.bin"
fi

echo ""
